<?php    
require_once(DIR_MODULES .'/media_files/media.class.php');

//$media = new media($_GET['id']);    

if($_SERVER['REQUEST_METHOD']=='POST'){    
  /* Handle File Upload FROM SWF UPload */
  if($_POST['PHPSESSID']!='' && $_FILES['Filedata']  ){
  
    // Its Upload from SWFUpload 
    
    $p = fopen(dirname(__FILE__) ."/upload.log","a+");
    fputs($p, print_r($_FILES,true));
    fputs($p, print_r($_SESSION,true));
    fputs($p, print_r($_POST,true));
    fputs($p , date("m/d/Y h:i A") ."\n");
    fclose($p);
	
	if(isset($_POST['id']))
	{
		// Prepare media for update
		$mediafile = new media($_POST['id']);
		$mediafile->delete();
		$_FILES['Filedata']['name'] = $_POST['id'];
	}

	// Upload media
	$mediafile = new media($_FILES['Filedata']);	
	$_SESSION['new_media_id'] = $mediafile->filename;	
	
    // Handle Page Creation    
    if($_POST['create_page'] =='1'){
      require_once(DIR_MODULES .'/pages/page.class.php');
      
      
      $new_page = new page();
      $page_fields['title'] = $_FILES['Filedata']['name'];
      $page_fields['content'] = '<h2>'. $_FILES['Filedata']['name'] .'</h2>'. "\n". '[gallery]';
      $page_fields['status'] = '1';
      $page_fields['parent_page'] = (int)$_POST['parent_page'];
      $page_fields['url_slug'] = make_url_slug($_FILES['Filedata']['name']);
      $page_fields['allow_comment'] = '1';
      
      $page_id = $new_page->save($page_fields);  
      
      $media->load($media->id);
      $new_page = new page($page_id);
      $new_page->add_media_by_resource($media->fields['resource_id'],$_FILES['Filedata']['name'] );
      
      // Create a Page Thumbnail;
      $resource = new resource($media->fields['resource_id']);
      
      try{
        $thumb = new cache_thumbnail($resource->filename, 200,200);
        $thumb_filename = $thumb->cache_path .'/'. $thumb->cache_filename;
        
        $new_page->set_thumbnail($thumb_filename);
        
      }catch(Exception  $e){
        
      }
    }
    if($_POST['add_to_page']=='1'){
      $page = new page($_POST['to_page']);
      $page->add_media_by_resource($media->fields['resource_id'],$_FILES['Filedata']['name'] );
              
    }
	  echo '1';
    exit;
  }
  
  // Post Validation
  if($_POST['delete']=='1')
  {
	if($_POST['media_id'])
	{
		$media_file = new media($_POST['media_id']);
		$media_file->delete();
		set_message("Media '". $_POST['media_id'] ."' deleted.");
		header("Location:". WWW_ROOT .'admin/modules/media_files');
		exit;  
	}  
  }
  
  
  
  if(trim($_POST['media']['title'])==''){
    $err['title'] = "Media title is required";
  }
   
   
   
  if(!$err){  
    if(isset($_GET['id'])){
      
      //$media->generate_preview();
      // Update
      if(true){//$media->update($_POST['media'])){
        set_message("Media Updated");
        reload_page();  
        exit;
      }
      
    }else{
      $new_media_id = $media->insert($_POST['media']);
      if($new_media_id){
        set_message("Media Added");
        header("Location:". WWW_ROOT  . 'admin/modules/media_files/edit_media?id='. $new_media_id);  
        exit;
      }
    
    }
  }
  
  
}else{
  // When it has new uploaded file, redirect the page to edit mode
  if(isset($_SESSION['new_media_id'])){
    $new_media_id = $_SESSION['new_media_id'];
    unset($_SESSION['new_media_id']);
    set_message("New Media Uploaded");
    header("Location:". WWW_ROOT  . 'admin/modules/media_files/edit_media?id='. $new_media_id);
    exit;
  }
  
  if($media->id){
    $_POST['media'] = $media->fields;  
  }

}


// Toolbar
$layout->add('toolbar','<a href="#" onclick="save_media(); return false;" class="button">Save Media</a>');
if($_GET['id']){
$layout->add('toolbar','<a href="#" onclick="delete_media(); return false;" class="button">Delete Media</a>');
  
}

// Session Message
$content.= show_session_message(true);


// Content
if(is_numeric($_GET['id'])){
  $content .= '<h2>Edit Media</h2>';
}else{
  $content .= '<h2>Add Media</h2>';
}

$content.='<form id="form_media" action="" method="POST" enctype="multipart-formdata">';
$content.='<input type="hidden" id="delete" name="delete" value="" />';
if(isset($_GET['id']))
	$content.='<input type="hidden" id="media_id" name="media_id" value="' . $_GET['id'] . '" />';
$content.='<fieldset>';

if(!isset($_GET['id'])){
  
  
  /* Show The uploader */
  
  /* Get parent page options */
  get_sub_pages_recursive(0, &$sub_pages );
  $parent_pages[] = "Root";
  $parent_page_values[] = 0;
  
  if($sub_pages){
    foreach($sub_pages as $e_page){
      $parent_pages[] = str_repeat('&nbsp;&nbsp;&nbsp;', $e_page['level']) . $e_page['title'];
      $parent_page_values[] = $e_page['page_id'];
    }
  }

  //$content.='<div class="set"><label>Create Page for each media upload</label><input type="checkbox" id="create_page" name="create_page" value="1" '.($_GET['create_page'] ==1?' checked':'').'/> Parent Page: '. select_input('parent_page', $_GET['parent_page'],$parent_pages, $parent_page_values)     .'</div>';
  //$content.='<div class="set"><label>Add to a Page</label><input type="checkbox" id="add_to_page" name="add_to_page" value="1" '.($_GET['add_to_page'] ==1?' checked':'').'/> Page: '. select_input('to_page', $_GET['to_page'],$parent_pages, $parent_page_values)     .'</div>';
  
  $content .='<p>Select a image file or video file<br/>(Supported type: jpg,gif,png,swf,flv,mov,mp3,mp4,doc)</p>';
  $content.='<div class="set"><label>Upload Media:</label>';
  $content.='<input type="file" id="media_uploader" name="Filedata" />';
  $content.='</div>';
  
  
}else{


  if($media_file = new media($_GET['id']))
  {	
	  // File Name
	  $content.='<div class="set"><label>File name:</label><div class="field"><a href="'. $media_file->get_url() .'">'. $media_file->filename .'</a></div></div>';
	  
	  // Size
	  $content.='<div class="set"><label>File size:</label><div class="field">'. number_format($media_file->filesize * 0.0009765625,2).' Kb</div></div>';
	  
	  // Preview
	  $thumbnail_url= resource_thumbnail_url($media->fields['preview_id']);
	  $content.='<div class="set"><label>Preview:</label><div class="field"><img src="'.$media_file->get_url().'" width="200px"></div></div>';
	  
	
	
	  // Title
	//  $content.= show_error($err['title']);
	//  $content.='<div class="set"><label class="required">Title:</label><input type="text" name="media[title]" value="' . htmlentities($_POST['media']['title']) .'" style="width:300px" /></div>';
	  
	  // Description
	//  $content.='<div class="set"><label>Description:</label><div class="field"><textarea name="media[description]" style="width:300px;height:100px">'. htmlentities($_POST['media']['description']) .'</textarea>
	//    <div class="note">HTML is OK</div>
	//  </div></div>';
	
	  // Category
	//  $media_categories = get_list_options('media_category',false);
	//  $content.='<div class="set"><label>Category:</label>'. select_input('media[category]',$_POST['media']['category'], $media_categories ) .'</div>';
	  
	
	
	
	  $content.='<div class="set"><label>Update Media:</label>';
	  $content.='<input type="file" id="media_uploader" name="Filedata" />';
	  $content.='</div>';
  }  
}

$content.='</fieldset>';
$content.='</form>';

$layout->add('content', $content);


// Additional Script / CSS
$layout->add('head','<script type="text/javascript" src="'.WWW_ROOT .'inc/swfupload/js/swfupload.js"></script>');
$layout->add('head','<script type="text/javascript" src="'.WWW_ROOT .'inc/swfupload/plugins/swfupload.cookies.js"></script>');
$layout->add('head','<script type="text/javascript" src="'.WWW_ROOT .'inc/swfupload/plugins/swfupload.queue.js"></script>');

$layout->add('head','<script type="text/javascript" src="'.WWW_ROOT .'js/jquery-asyncupload/jquery-asyncUpload-0.1.js"></script>');
// $layout->add('head','<script type="text/javascript" src="'.WWW_ROOT .'js/jquery-asyncupload/swfupload.js"></script>'); // older swfupload script



require_once(DIR_INCLUDE .'/jsonwrapper/jsonwrapper.php');
$_SESSION['_COOKIE'] = serialize($_COOKIE);

//print_r($_SESSION);
session_write_close();

$js = '<script type="text/javascript">

function init_media_uploader() {
//return;
  
  var _GET = '. json_encode($_GET) .';
  
  $("#media_uploader").makeAsyncUploader({
      upload_url: WWW_ROOT + "admin/modules/media_files/edit_media", 
      flash_url: WWW_ROOT + "js/jquery-asyncupload/swfupload.swf",
      //flash_url: WWW_ROOT + "inc/swfupload/Flash/swfupload.swf", // v2.2
      button_image_url: WWW_ROOT + "js/jquery-asyncupload/blankButton.png",
      //debug: true,
      post_params : _GET,
      upload_complete_handler:function(){ return true; },
      queue_complete_handler:function(){ window.location.reload(); }
  });
}        

</script>';

$layout->add('head','
<style>
DIV.ProgressBar { width: 100px; padding: 0; border: 1px solid black; margin-right: 1em; height:.75em; margin-left:1em; display:-moz-inline-stack; display:inline-block; zoom:1; *display:inline; }
DIV.ProgressBar DIV { background-color: Green; font-size: 1pt; height:100%; float:left; }
SPAN.asyncUploader OBJECT { position: relative; top: 5px; left: 10px; }
</style>');

$layout->add('head',$js);
$layout->add('head', '<script type="text/javascript" src="'.WWW_MODULES .'/media/js/edit_media.js"></script>');


/* Helper functions 
*****************************************/
function show_error($str){
  if($str !=''){
    return '<p class="error">'. $str . '</p>';
  }  
}


function get_sub_pages_recursive($page_id=0, &$passing, $current_id=''){
  get_sub_pages($page_id, 0, &$passing, $current_id);
  
}

function get_sub_pages($parent_id=0, $level=0, &$passing, $current_id){
  
  if($current_id===$parent_id) return;
  //if($parent_id==0) unset($passing);
  
  $query = "SELECT * from pages where parent_page='". $parent_id ."' order by page_order, page_id";
  $rsconn = db_query($query,true);
  if($rsconn){
    foreach($rsconn as $rec){
      $rec['level'] = $level;
      if($rec['page_id']!= $current_id){
        $passing[] = $rec; 
      }
      get_sub_pages($rec['page_id'], $level + 1, &$passing, $current_id);   
    }  
  }
 
}

function make_url_slug($str){
  $str = ereg_replace('[^A-Za-z0-9 ]+','',$str);
  $str = strtolower(str_replace(" ","_", $str));

  return $str;
}
?>